import Token from '../../utils/token';
import { PASSWORDERROR, USERNOEXIST } from '../../utils/error';
const fs = require('fs');
const path = require('path');
const rename = think.promisify(fs.rename, fs);
const assert = require('assert');
const BasicController = require('../BasicController.js');

module.exports = class extends BasicController {
  constructor(ctx) {
    super(ctx);
    assert(think.isFunction(this.model), 'this.model must be a function');
    this.MODEL = this.ctx.state.ApiInfo.model;
    this.params = {
      model: this.MODEL,
      data: this.post()
    };
  }
  async editstateAction() {
    const params = this.params;
    const databack = await this.model(this.MODEL).editstateAction(params);
    return this.success(databack, 'ok');
  }
  async loginAction() {
    // 根据账号查找用户
    // console.log('controller: user/user/login');
    const params = this.params;
    const data = await this.model(this.MODEL).loginAction(params);
    if (Object.keys(data).length === 0) {
      Object.assign(this.ctx, USERNOEXIST);
      return;
    }
    if (data.password !== this.params.data.password) {
      Object.assign(this.ctx, PASSWORDERROR);
      return;
    }
    delete data.password;
    // 生成token */
    const token = Token.createToken(data);
    this.header('token', token);
    data.token = token;
    return this.success(data, '登录成功');
  }
  async currentAction() {
    const data = this.ctx.state.UserInfo;
    data.infoState = 0;
    if (data.user_level === 0) {
      const datacheck = await this.model('student_info').where({stu_id: data.id}).find();
      data.userinfo = datacheck;
      if (datacheck.stu_name === '' || datacheck.stu_num === '' || datacheck.stu_tel === '') {
        return this.success(data, 'noinfo');
      } else {
        data.infoState = 1;
        return this.success(data, 'fullinfo');
      }
    } else {
      const databack = await this.model('teacher_info').where({teacher_id: data.id}).find();
      data.userinfo = databack;
      return this.success(data);
    }
    // ctx.fail(errno, errmsg, data)
    // ctx.success(data, message)
  }
  async imguploadAction() {
    const data = this.post();
    const file = this.file().file;
    const filedata = {};
    const firstname = think.md5(file.name);
    const lastname = path.extname(file.name);
    const name = `${firstname}${lastname}`;
    // 传多张图片
    // for (const i in file) {
    //   if (Object.prototype.toString.call(file[i]) === '[object Array]') {
    //     for (const value of file[i]) {
    //       filepath = path.join(think.ROOT_PATH, `runtime/upload/imgInfo/${data.id}/${value.name}`);
    //       think.mkdir(path.dirname(filepath));
    //       await rename(value.path, filepath);
    //     }
    //   // 同名 -> 数组
    //   } else if (Object.prototype.toString.call(file[i]) === '[object Object]') {
    //     filepath = path.join(think.ROOT_PATH, `runtime/upload/imgInfo/${data.id}/${file[i].name}`);
    //     think.mkdir(path.dirname(filepath));
    //     await rename(file[i].path, filepath);
    //   // 不同名 ->对象
    //   }
    // }
    const filepath = path.join(think.ROOT_PATH, `runtime/upload/imgInfo/${data.id}/${name}`);
    think.mkdir(path.dirname(filepath));
    await rename(file.path, filepath);
    // 上传单张图片
    const fileid = think.uuid('v4');
    filedata.id = fileid;
    filedata.file_path = filepath;
    filedata.user_id = data.id;
    await this.model('user_files').add(filedata);
    this.success({id: fileid}, 'ok');
  }
  // async downloadAction() {
  //   // const file = this.file();
  //   // console.log(file);
  //   // const data = this.post();
  //   // console.log(data);
  //   const filepath = path.join(think.ROOT_PATH, 'runtime/upload/imgInfo/db35d222ff1d07b0fab50fa44272c1b151213d8315343-Y0bPkG_fw658.jpeg');
  //   this.ctx.download(filepath);
  //   return this.success(filepath);
  // }
  async delimgAction() {
    const data = this.params.data;
    const backdata = await this.model('user_files').where(data).delete();
    this.success(backdata, 'ok');
  }
  async resetAction() {
    const params = {
      model: 'studentInfo',
      data: this.params.data
    };
    const data = await this.model('student_info').listallAction(params);
    params.resetdata = data;
    params.model = this.MODEL;
    if (Object.keys(data).length === 0) {
      return this.fail('信息错误，无法提供重置');
    } else {
      await this.model(this.MODEL).resetAction(params);
      return this.success('', 'ok');
    }
  }
};
/**
 * @api {POST} /user/user/login /login
 * @apiName login
 * @apiGroup user
 * @apiParam {String} num 学号
 * @apiParam {String} password 密码

 *
 * @apiSuccessExample 请求成功demo:
 *     HTTP/1.1 200 OK
 *     {
 *       {
    "errno": 0,
    "errmsg": "ok",
    "data": 1
}
 *     }
 *
 *
 * @apiErrorExample 请求失败返回demo:
 *     HTTP/1.1 404 Not Found
 *     {
 *           "errno": 0,
    "errmsg": "",
    "data": {
        "id": "1",
        "num": "5120152623",
        "role_id": "1"
    }
 *     }
 * @apiParamExample {post} Request-Example:
                 {
                    num:5120152623,
                    password:123456
                  }
 */
/**
 * @api {POST} /user/user/reset /reset
 * @apiName reset
 * @apiGroup user
 * @apiParam {String} stu_num 学号(8-10位)
 * @apiParam {String} stu_name 姓名
 * @apiParam {String} stu_tel 手机号
 *
 * @apiSuccessExample 请求成功demo:
 *     HTTP/1.1 200 OK
 *     {
 *       {
     "code": 0,
    "msg": "ok",
    "data": ""
}
 *     }
 *
 *
 * @apiErrorExample 请求失败返回demo:
 *     HTTP/1.1 404 Not Found
 *     {
 *           "errno": 0,
    "errmsg": "信息错误，无法提供重置",
 *     }
 * @apiParamExample {post} Request-Example:
                 {
                    stu_num:11111,
                    stu_name:dd,
                    stu_tel:*******
                  }
 */
/**
 * @api {POST} /user/user/add /add
 * @apiName add
 * @apiGroup user
 * @apiParam {String} num 学号
 * @apiParam {string} role_id 角色ID
 * @apiParam {String} password 密码
 * @apiParam {number} user_level 用户级别
 * @apiParam {number} user_state 用户状态

 *
 * @apiSuccessExample 请求成功demo:
 *     HTTP/1.1 200 OK
 *     {
 *       {
    "errno": 0,
    "errmsg": "ok",
    "data": 1
}
 *     }
 *
 *
 * @apiErrorExample 请求失败返回demo:
 *     HTTP/1.1 404 Not Found
 *     {
 *        erro
 *     }
 * @apiParamExample {post} Request-Example:
                 {
                    num:5120157551,
                    role_id:3,
                    password:123456
                  }
 */
/**
 * @api {DELETE} /user/user/del /del
 * @apiName del
 * @apiGroup user
 * @apiParam {string} id 用户ＩＤ
 * @apiSuccessExample 请求成功demo:
 *     HTTP/1.1 200 OK
 *     {
 *       {
    "errno": 0,
    "errmsg": "ok",
    "data": 1
}
 *     }
 *
 *
 * @apiErrorExample 请求失败返回demo:
 *     HTTP/1.1 404 Not Found
 *     {
 *        erro
 *     }
 * @apiParamExample {post} Request-Example:
                 {
                    id:1;
                  }
 */
/**
 * @api {POST} /user/user/listall /listall
 * @apiName listall
 * @apiGroup user
 * @apiSuccessExample 请求成功demo:
 *     HTTP/1.1 200 OK
 *     {
 *       {
    "errno": 0,
    "errmsg": "ok",
    "data": [
        {
            "id": 2,
            "num": "5120157550",
            "role_id": "3",
            "password": "123456"
        },
        {
            "id": 3,
            "num": "admin1234",
            "role_id": "1",
            "password": "88888888"
        },
        {
            "id": 4,
            "num": "5120150000",
            "role_id": "3",
            "password": "123456"
        }
    ]
}
 *     }
 *
 *
 * @apiErrorExample 请求失败返回demo:
 *     HTTP/1.1 404 Not Found
 *     {
 *        erro
 *     }
 * @apiParamExample {get} Request-Example:
                 {}
 */
/**
 * @api {POST} /user/user/edit /edit
 * @apiName edit
 * @apiGroup user
 * @apiParam {string} id 用户ＩＤ
 * @apiParam {String} [password] 密码
 * @apiParam {string} [role_id] 角色ＩＤ
 * @apiSuccessExample 请求成功demo:
 *     HTTP/1.1 200 OK
 *     {
 *       {
    "errno": 0,
    "errmsg": "ok",
    "data": [
        {
            "id": 2,
            "num": "5120157550",
            "role_id": "3",
            "password": "123456"
        },
        {
            "id": 3,
            "num": "admin1234",
            "role_id": "1",
            "password": "88888888"
        },
        {
            "id": 4,
            "num": "5120150000",
            "role_id": "3",
            "password": "123456"
        }
    ]
}
 *     }
 *
 *
 * @apiErrorExample 请求失败返回demo:
 *     HTTP/1.1 404 Not Found
 *     {
 *        erro
 *     }
 * @apiParamExample {post} Request-Example:
                 {}
 */
/**
 * @api {GET} /user/user/get /get
 * @apiName get
 * @apiGroup user
 * @apiParam {string} id 用户ＩＤ
 * @apiSuccessExample 请求成功demo:
 *     HTTP/1.1 200 OK
 *     {
 *       {
    "errno": 0,
    "errmsg": "ok",
    "data": [
        {
            "id": 2,
            "num": "5120157550",
            "role_id": "3",
            "password": "123456"
        }
    ]
}
 *     }
 *
 *
 * @apiErrorExample 请求失败返回demo:
 *     HTTP/1.1 404 Not Found
 *     {
 *        erro
 *     }
 * @apiParamExample {get} Request-Example:
                 {
                   id : 2
                 }
 */
/**
 * @api {GET} /user/user/current /current
 * @apiName current
 * @apiGroup user
 * @apiSuccessExample 请求成功demo:
 *     HTTP/1.1 200 OK
 *     {
 *       {
    "errno": 0,
    "errmsg": "fullinfo",
    "data": [
        {
            "id": 2,
            "num": "5120157550",
            "role_id": "3",
            "password": "123456"
            infoState:1
        }
    ]
}
 *     }
 *
 *
 * @apiErrorExample 请求失败返回demo:
 *     HTTP/1.1 404 Not Found
 *     {
 *        erro
 *     }
 * @apiParamExample {get} Request-Example:
                 {
                 }
 */
/**
  * @api {POST} /user/user/imgupload /imgupload
 * @apiName imgupload
 * @apiGroup user
 * @apiParam {string} id 用户ID
 * @apiSuccessExample 请求成功demo:
 *     HTTP/1.1 200 OK
 *     {
 *       {
 *   "errno": 0,
 *   "errmsg": "ok",
 *   "data": [
 *     {
 *   }
 *  ]
 *
 *}
 *
 *
 * @apiErrorExample 请求失败返回demo:
 *     HTTP/1.1 404 Not Found
 *     {
 *        "errno": 404,
 *        "errmsg": "请求路径错误",
 *        "data": 7
 *     }
 * @apiParamExample {post} Request-Example:
 * { '1':
   [ File {
       _events: {},
       _eventsCount: 0,
       _maxListeners: undefined,
       size: 144664,
       path: '/home/d/Code/mobile_internet_website_server/upload_aac77b2809d35bf661f3dd2f34d4a661.png',
       name: '新数据库.png',
       type: 'image/png',
       hash: null,
       lastModifiedDate: 2018-08-02T08:04:54.943Z,
       _writeStream: [WriteStream] },
     File {
       _events: {},
       _eventsCount: 0,
       _maxListeners: undefined,
       size: 304329,
       path: '/home/d/Code/mobile_internet_website_server/upload_4b90e3a3d243d52828eaff0d72a9cfea.png',
       name: '1.png',
       type: 'image/png',
       hash: null,
       lastModifiedDate: 2018-08-02T08:04:54.964Z,
       _writeStream: [WriteStream] } ] }
  */
/**
  * @api {POST} /user/user/download /download
 * @apiName download
 * @apiGroup user
 * @apiParam {string} userid 用户ID
 * @apiSuccessExample 请求成功demo:
 *     HTTP/1.1 200 OK
 *     {
 *       {
 *   "errno": 0,
 *   "errmsg": "ok",
 *   "data": [
 *     {
 *      filepath: "///.jpeg"
 *   }
 *  ]
 *
 *}
 *
 *
 * @apiErrorExample 请求失败返回demo:
 *     HTTP/1.1 404 Not Found
 *     {
 *        "errno": 404,
 *        "errmsg": "请求路径错误",
 *        "data":
 *     }
 * @apiParamExample {post} Request-Example:
 * {
 *  id:1
 * }
  */
/**
  * @api {POST} /user/user/delimg /delimg
 * @apiName delimg
 * @apiGroup user
 * @apiParam {string} id 图片ID
 * @apiSuccessExample 请求成功demo:
 *     HTTP/1.1 200 OK
 *     {
 *       {
 *   "errno": 0,
 *   "errmsg": "ok",
 *   "data": [
 *     {
 *      filepath: "///.jpeg"
 *   }
 *  ]
 *
 *}
 *
 *
 * @apiErrorExample 请求失败返回demo:
 *     HTTP/1.1 404 Not Found
 *     {
 *        "errno": 404,
 *        "errmsg": "请求路径错误",
 *        "data":
 *     }
 * @apiParamExample {post} Request-Example:
 * {
 *  id:**************
 * }
  */
/**
  * @api {POST} /user/user/editstate /editstate
 * @apiName editstate
 * @apiGroup user
 * @apiParam {string} id 用户ID
 * @apiParam {number} [user_state] 1:审核通过/0：未通过
 * @apiSuccessExample 请求成功demo:
 *     HTTP/1.1 200 OK
 *     {
 *       {
 *   "errno": 0,
 *   "errmsg": "ok",
 *   "data": [
 *     {
 *       "code": 0,
    "msg": "ok",
    "data": 1
 *   }
 *  ]
 *
 *}
 *
 *
 * @apiErrorExample 请求失败返回demo:
 *     HTTP/1.1 404 Not Found
 *     {
 *        "errno": 404,
 *        "errmsg": "请求路径错误",
 *        "data":
 *     }
 * @apiParamExample {post} Request-Example:
 * {
 *  id:１，
 *  user_state: 1
 * }
  */
